package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.StorageRecord;
import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.StorageRecordService;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.service.impl.SysUserServiceImpl;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("main/storageRecord")
public class StorageRecordController extends BaseController{
    private static final Logger LOGGER= LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private StorageRecordService storageRecordService;
    @Autowired
    private SupplierService supplierService;

    @RequestMapping(value = "/page",produces = "application/json;charset=UTF-8")
    public String page(Model model, StorageRecord condition,
                       @RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo,
                       @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize){
        Page<StorageRecord> page=null;
        try {
            page=storageRecordService.findPage(condition,pageNo,pageSize);
            List<Supplier> supplierList=supplierService.findAll();

            model.addAttribute("pageInfo",page);
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("condition",condition);
        }catch (Exception e){
            LOGGER.error("StorageRecordController中的page方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/page";
    }

    @GetMapping("/save")
    public String toSave(Model model){
        List<Supplier> supplierList=null;
        try {
            supplierList=supplierService.findAll();
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("storageRecord",new StorageRecord());
        }catch (Exception e){
            LOGGER.error("SysUserController中的toSave方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }

    @PostMapping("/save")
    public String doSave(StorageRecord storageRecord){
        try {
            SysUser loginUser=session(Constants.SESSION_USER);
            if ((storageRecord.getId()==null)){
                storageRecord.setCreatedUserId(loginUser.getId());
                storageRecord.setCreatedTime(new Date());
            }else {
                storageRecord.setUpdatedUserId(loginUser.getId());
                storageRecord.setUpdatedTime(new Date());
            }

            boolean ok=storageRecordService.saveOrUpdate(storageRecord);
            if (ok){
                if (storageRecord.getId()==null){
                    return redirect("/main/storageRecord/page");
                }else {
                    storageRecord.setSupplier(supplierService.findById(storageRecord.getSupplierId()));

                    return "/storageRecord/view";
                }
            }
        }catch (Exception e){
            LOGGER.error("StorageRecordController中的doSave方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }

    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model){
        StorageRecord storageRecord=null;
        try {
            storageRecord=storageRecordService.findById(id);
            model.addAttribute("storageRecord",storageRecord);
        }catch (Exception e){
            LOGGER.error("StorageRecordController中的view方法执行发生错误",e);
            throw new RuntimeException(e);
        }

        return "storageRecord/view";
    }

    @ResponseBody
    @GetMapping("/srCodeExist")
    public String srCodeExist(@RequestParam("srCode") String srCode){
        LOGGER.info("检查入库编号srCode={}的商品是否存在",srCode);
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        if (StringUtils.isEmpty(srCode)){
            resultMap.put("exist",0);
        }else {
            try {
                StorageRecord storageRecord=storageRecordService.findBySrCode(srCode);
                if (null!=storageRecord){
                    resultMap.put("exist",1);
                }else {
                    resultMap.put("exist",0);
                }
            }catch (Exception e){
                LOGGER.error("StorageRecordController中的srCodeExists方法执行发生错误。",e);
                resultMap.put("error","出现异常，请联系管理员处理");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @GetMapping(value = "/{id}/view",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map ajaxView(@PathVariable("id") Long id){
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        StorageRecord info=null;
        try {
            info=storageRecordService.findById(id);
            if(info!=null){
                resultMap.put("code",200);
                resultMap.put("data",info);
            }else{
                resultMap.put("code",500);
            }
        }catch (Exception e){
            LOGGER.error("StorageRecordController中的ajaxView方法执行错误。",e);
            resultMap.put("code",500);
        }
        return resultMap;
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id,Model model){
        StorageRecord storageRecord=null;
        List<Supplier> supplierList=null;
        try {
            storageRecord=storageRecordService.findById(id);
            supplierList=supplierService.findAll();
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("storageRecord",storageRecord);
        }catch (Exception e){
            LOGGER.error("StorageRecordController中的toEdit方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }

    @DeleteMapping( "/del/{id}")
    @ResponseBody
    public String del(@PathVariable("id") Long id){
        try {
            int count=storageRecordService.deleteById(id);
            return ajaxResult();
        }catch (Exception e){
            LOGGER.error("StorageRecordController中的del方法执行发生错误",e);
            throw new RuntimeException(e);
        }
    }
}


